package com.campus.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.api.util.UserContext;
import com.campus.campus.job.dto.LossRecordDTO;
import com.campus.campus.job.entity.CampusCards;
import com.campus.campus.job.entity.LossRecord;
import com.campus.campus.job.entity.TransactionDetail;
import com.campus.campus.job.vo.CampusCardsInfoVO;
import com.campus.campus.job.vo.TransactionDetailVO;
import com.campus.campus.mapper.CampusCardsMapper;
import com.campus.campus.mapper.LossRecordMapper;
import com.campus.campus.mapper.TransacitionDetailMapper;
import com.campus.campus.service.ICampusCardsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.exception.ServiceException;
import com.campus.common.result.Result;
import com.campus.common.student.job.entity.Student;
import com.campus.common.student.mapper.StudentMapper;
import com.campus.common.teacher.job.entity.Teacher;
import com.campus.common.teacher.mapper.TeacherMapper;
import com.campus.common.user.entity.pojo.User;
import com.campus.common.user.mapper.AuthMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 校园卡表 服务实现类
 * </p>
 *
 * @author mwb
 * @since 2024-11-17
 */
@Service
public class CampusCardsServiceImpl extends ServiceImpl<CampusCardsMapper, CampusCards> implements ICampusCardsService {

    @Autowired
    private CampusCardsMapper campusCardsMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private TransacitionDetailMapper transacitionDetailMapper;

    @Autowired
    private LossRecordMapper lossRecordMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    /**
     *查询校园卡信息
     */
    @Override
    public CampusCardsInfoVO getCampusCardInfo() {
        int userId = UserContext.getUserId();
        User user = authMapper.selectById(userId);
        if (Optional.ofNullable(user).isEmpty()) {
            throw new ServiceException("未查询到该用户信息");
        }

        CampusCardsInfoVO vo = new CampusCardsInfoVO();
        vo.setName(user.getName());
        vo.setSex(user.getSex());
        vo.setImage(user.getImage());
        vo.setIdentity(user.getIdentity());
        if (user.getIdentity() == 0) {
            Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>()
                    .eq(Student::getUserId, userId));
            if (student == null) {
                throw new ServiceException("未查询到该用户信息");
            }
            vo.setStudentId(student.getId());
            vo.setCollege(student.getCollege());

        } else if (user.getIdentity() == 1) {
            Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>()
                    .eq(Teacher::getUserId, userId));
            if (teacher == null) {
                throw new ServiceException("未查询到该用户信息");
            }
            vo.setWorkId(user.getWorkId());
            vo.setCollege(teacher.getAcademy());
        }

        return vo;

    }

    /**
     * 查询余额及交易记录
     */
    @Override
    public List<TransactionDetailVO> getTransactionRecord() {
        int userId = UserContext.getUserId();
        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>()
                .eq(Student::getUserId, userId));
        if (Optional.ofNullable(student).isEmpty()) {
            throw new ServiceException("未查询到该学生信息");
        }
        List<TransactionDetail> transactionDetails = transacitionDetailMapper.selectList(new LambdaQueryWrapper<TransactionDetail>()
                .eq(TransactionDetail::getStudentId, student.getId()));

        CampusCards campusCards = campusCardsMapper.selectOne(new LambdaQueryWrapper<CampusCards>()
                .eq(CampusCards::getStudentId, student.getId()));
        if (Optional.ofNullable(campusCards).isEmpty()) {
            throw new ServiceException("未查询到该学生校园卡信息");
        }
        List<TransactionDetailVO> list = new ArrayList<>();
        if (transactionDetails.isEmpty()) {
            TransactionDetailVO vo = new TransactionDetailVO();
            vo.setBalance(campusCards.getBalance());
            list.add(vo);
            return list;
        }
        for (TransactionDetail transactionDetail : transactionDetails) {
            TransactionDetailVO vo = new TransactionDetailVO();
            BeanUtils.copyProperties(transactionDetail, vo);
            vo.setBalance(campusCards.getBalance());
            list.add(vo);
        }
        return list;
    }

    /**
     * 校园卡挂失
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void lossCard(LossRecordDTO lossRecordDTO) {
        int userId = UserContext.getUserId();
        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>()
                .eq(Student::getUserId, userId));
        if (Optional.ofNullable(student).isEmpty()) {
            throw new ServiceException("未查询到该学生信息");
        }

        if (lossRecordDTO.getName() == null || lossRecordDTO.getStudentId() == null || lossRecordDTO.getIdentityCard() == null) {
            throw new ServiceException("请填写完整的挂失信息");
        }

        CampusCards campusCards = campusCardsMapper.selectOne(new LambdaQueryWrapper<CampusCards>()
                .eq(CampusCards::getStudentId, student.getId()));
        if (Optional.ofNullable(campusCards).isEmpty()) {
            throw new ServiceException("未查询到该学生校园卡信息");
        }

        //将原校园卡数据 移到 新校园卡
        CampusCards newCampusCards = new CampusCards();
        newCampusCards.setStudentId(campusCards.getStudentId());
        newCampusCards.setBalance(campusCards.getBalance());
        int insert = campusCardsMapper.insert(newCampusCards);
        if (insert < 1) {
            throw new ServiceException("学生校园卡信息更新失败");
        }

        //删除原校园卡数据
        int deleted = campusCardsMapper.deleteById(campusCards.getId());
        if (deleted < 1) {
            throw new ServiceException("删除该学生校园卡信息失败");
        }

        LossRecord lossRecord = new LossRecord();
        BeanUtils.copyProperties(lossRecordDTO, lossRecord);
        lossRecord.setCardId(campusCards.getId());
        lossRecord.setStudentId(campusCards.getStudentId());
        lossRecord.setCreateTime(LocalDateTime.now());
        int row = lossRecordMapper.insert(lossRecord);
        if (row < 1) {
            throw new ServiceException("校园卡挂失失败");
        }

    }

    @Override
    public Result getBalance() {

        int userId = UserContext.getUserId();
        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>()
                .eq(Student::getUserId, userId));
        if (Optional.ofNullable(student).isEmpty()) {
            throw new ServiceException("未查询到该学生信息");
        }

        LambdaQueryWrapper<CampusCards> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CampusCards::getStudentId, student.getId());

        CampusCards campusCards = campusCardsMapper.selectOne(queryWrapper);

        if(Optional.ofNullable(campusCards).isEmpty()){
            return Result.fail("未查询到该学生校园卡信息");
        }
        return Result.success(campusCards.getBalance());

    }
}
